package edu.uestc.wsn;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Joseph
 * @since May 4,2012
 */
public class Communicator extends Thread {
    private boolean running = true;
    /**
     * 通訊服務器團口
     */
    private static int port = Constant.port;
    /**
     * 監聽的Socket
     */
    ServerSocket listener;
    /**
     * 服務端Socket
     */
    private Socket server;
    /**
     * 接受到的點的集合
     */
    private Map<String, LocRss> map;

    // Listen for incoming connections and handle them
    public Communicator() {
        map = new HashMap<String, LocRss>();  //初始化
        try {
            listener = new ServerSocket(port);//在port端口建立socket監聽
            System.out.println("listening at port " + port);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            while (this.running) {
                System.out.println("enter the communicator");

                server = listener.accept();//接受到一個socket數據
                System.out.println("accept at port:" + port);
                // Get input from the client
                ObjectInputStream inputStream = new ObjectInputStream((server
                        .getInputStream()));
                LocRss locRss = (LocRss) inputStream.readObject(); //接受LocRss數據
                System.out.println("receiving " + locRss.getName());
                map.put(locRss.getName(), locRss);//更新點集合
            }
            server.close();//所有結束後，關閉服務器socket
        } catch (Exception ioe) {
            ioe.printStackTrace();
        }
    }

    public void setRunning(boolean running) {
        this.running = running;
    }

    public Map<String, LocRss> getMap() {
        return map;
    }


}
